package com.lp.multi.juc.collection.unsafe;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author: lp
 * @create: 2021-06-27 15:44
 * @description: Map不安全测试
 * 安全策略：
 * 1.Collections.synchronizedMap()
 * 2.HashTable
 * 3.ConcurrentHashMap
 */
public class MapTest {
    public static void main(String[] args) throws InterruptedException {
        Map<String,String> map = new HashMap<String,String>();
        for (int i = 0; i < 1000; i++) {
            final int temp = i;
            new Thread(()->{
                map.put(String.valueOf(temp),String.valueOf(temp));
                System.out.println(map);
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(map.size());
    }
}

class SafeCollectionsMapTest{
    public static void main(String[] args) throws InterruptedException {
        Map<String,String> map = Collections.synchronizedMap(new HashMap<String,String>());
        for (int i = 0; i < 1000; i++) {
            final int temp = i;
            new Thread(()->{
                map.put(String.valueOf(temp),String.valueOf(temp));
                System.out.println(map);
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(map.size());
    }
}

class SafeConcurrentHashMapTest{
    public static void main(String[] args) throws InterruptedException {
        Map<String,String> map = new ConcurrentHashMap<>();
        for (int i = 0; i < 1000; i++) {
            final int temp = i;
            new Thread(()->{
                map.put(String.valueOf(temp),String.valueOf(temp));
                System.out.println(map);
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(map.size());
    }
}

class SafeHashTableTest{
    public static void main(String[] args) throws InterruptedException {
        Map<String,String> map = new Hashtable<>();
        for (int i = 0; i < 1000; i++) {
            final int temp = i;
            new Thread(()->{
                map.put(String.valueOf(temp),String.valueOf(temp));
                System.out.println(map);
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(5);
        System.out.println(map.size());
    }
}